package com.mriassl.stream.web.wsocket;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@ServerEndpoint("/ws/index")
@Component
public class IndexServer {

    private static Logger logger = LoggerFactory.getLogger(IndexServer.class);

    private static Map<String, List<Session>> SESSION_POOL = new ConcurrentHashMap<>();
    private static String DEFAULT_SESSION_KEY = "USER_PK";

    @OnOpen
    public void onOpen(Session session) throws IOException {
        String key = getKey(session);
        if (StringUtils.isNotBlank(key)) {
            List<Session> list = SESSION_POOL.computeIfAbsent(key, k -> new ArrayList<>());
            list.add(session);
        }
    }

    @OnMessage
    public void onMessage(String message, Session session) {

    }

    @OnError
    public void onError(Throwable throwable) {
        logger.error(throwable.getMessage());
    }

    @OnClose
    public void onClose(Session session) {
        String key = getKey(session);
        if (StringUtils.isNotBlank(key)) {
            SESSION_POOL.remove(key);
        }
    }

    /**
     * 获取回话标识
     * @Title: getKey
     * @author soar
     * @param @param session
     * @param @return    参数
     * @return String    返回类型
     * @throws
     */
    private String getKey(Session session) {
        Map<String, List<String>> requestParameterMap = session.getRequestParameterMap();
        String key = null;
        List<String> list = requestParameterMap.get(DEFAULT_SESSION_KEY);
        if (list != null && !list.isEmpty()) {
            key = list.get(0);
        }
        return key;
    }

    public static List<Session> getSession(String key) {
        return SESSION_POOL.get(key);
    }

}
